/**
 * 验证码登陆gongnne
 */
package com.catsic.security.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

public class CatsicUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
	public static final String SPRING_SECURITY_FORM_CAPTCHA_KEY = "captcha";
	private String captchaParameter = SPRING_SECURITY_FORM_CAPTCHA_KEY;
	
	/**
	 * LogsService:日志logsService
	 */
	/*@Autowired
	private LogsService logsService;*/
	
	public CatsicUsernamePasswordAuthenticationFilter() {
		super();
	}

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request,
			HttpServletResponse response) throws AuthenticationException {

		String captcha = obtainCaptcha(request);  
	    String genCaptcha = (String)request.getSession().getAttribute("rand");
	    long time = request.getSession().getAttribute("time") == null ? 0 : (long)request.getSession().getAttribute("time");  
	    request.getSession().removeAttribute("time");
	    if(StringUtils.isBlank(genCaptcha)){
	    	throw new BadCredentialsException("验证码无效");  
	    }
	     
	    /**
	     * 验证码超时，2分钟
	     */
	    if((System.currentTimeMillis() - time) / (1000 * 60) > 2){
	    	throw new BadCredentialsException("验证码超时");  
	    }
	    
	    if(!StringUtils.equals(genCaptcha, captcha)){  
	        throw new BadCredentialsException("验证码错误");  
	    }  
	    Authentication authentication = super.attemptAuthentication(request, response);
	    /**
	     * 用户名，密码方式登录需要此处记录，否则登录操作无IP地址显示，其他IP地址记录在CatsicConcurrentSessionControlStrategy类中，
	     */
/*	    UserInfo userInfo = (UserInfo) authentication.getPrincipal();
	    userInfo.setIp(NetworkUtil.getIpAddress(request));*/
	    /**
	     * 登录成功后记录日志
	     */
	    //logsService.add(userInfo,"系统管理","登录","成功");
		return authentication;
	}
	
	protected String obtainCaptcha(HttpServletRequest request) {
		return request.getParameter(captchaParameter);
	}
}
